package com.amigo.online.provider.ffmpeg.rocketmq;

import com.amigo.online.provider.ffmpeg.rocketmq.config.RocketMqProperties;
import com.amigo.online.provider.ffmpeg.rocketmq.model.BaseMqSendModel;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

@Service
public class RocketMqUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    public static SendResult send(BaseMqSendModel baseMqSendModel) throws Exception {
        DefaultMQProducer producer = (DefaultMQProducer) context.getBean(RocketMqProperties.DEFAULT);
        Message msg = new Message(RocketMqProperties.DEFAULT_TOPIC, baseMqSendModel.getTag(),
                getRandomKey(), JSON.toJSONBytes(baseMqSendModel));
        SendResult r = producer.send(msg, 2000);
        return r;
    }

    private static String getRandomKey() {
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange('a', 'z').build();
        return generator.generate(10);
    }

    public DefaultMQProducer getDefaultMQProducer() {
        return (DefaultMQProducer) context.getBean(RocketMqProperties.DEFAULT);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;

    }

}
